import * as types from './mutation-types'
import Vue from 'vue'
function update (target, current) {
  for (let i in current) {
    Vue.set(target, i, current[i])
  }
}
export default {
  // 添加工单or新建工单
  [types.FLOW_CHANGE_TYPE] (state, data) {
    state.currentType = data
  },
  // 变更工单步骤或工单动作index
  [types.CHANGE_CURRENT_INDEX] (state, data) {
    let type = state.currentType
    update(state[type], data)
  },
  // 变更工单信息
  [types.UPDATE_FLOW_INFO] (state, data) {
    let type = state.currentType
    if (data.type === 'update') {
      update(state[type].flowInfo, data.data)
    } else if (data.type === 'replace') {
      Vue.set(state[type], 'flowInfo', data.data)
    }
  },
  // 变更工单信息
  [types.UPDATE_STEP_INFO] (state, data) {
    let currentType = state.currentType
    let currentStepId = state[currentType].currentStepIndex
    update(state[currentType].flowSteps[currentStepId], data)
  },
  // 更新工单步骤
  [types.UPDATE_FLOW_STEP] (state, data) {
    let currentType = state.currentType
    let flowSteps = state[currentType].flowSteps
    // 添加步骤
    if (data.type === 'add') {
      flowSteps.push(data.data)
    } else if (data.type === 'update') {
      // 更新步骤
      let currentStepId = state[currentType].currentStepIndex
      update(flowSteps[currentStepId], data.data)
    } else if (data.type === 'replace') {
      Vue.set(state[currentType], 'flowSteps', data.data)
    }
  },
  // 更新工单动作
  [types.UPDATE_FLOW_ACTION] (state, data) {
    let currentType = state.currentType
    let flowSteps = state[currentType].flowSteps
    let currentStepIndex = state[currentType].currentStepIndex
    let actions = flowSteps[currentStepIndex].actions
    // 添加步骤
    if (data.type === 'add') {
      actions.push(data.data)
    } else if (data.type === 'update') {
      // 更新步骤
      let currentActionIndex = state[currentType].currentActionIndex
      update(actions[currentActionIndex], data.data)
    } else if (data.type === 'delete') {
      actions.splice(data.data, 1)
    }
  },
  // 更新工单字段
  [types.UPDATE_FLOW_FIELD] (state, data) {
    let currentType = data.currentType || state.currentType
    // 添加步骤
    if (data.type === 'add') {
      state[currentType].allFields.push(data.data)
    } else if (data.type === 'update') {
      state[currentType].allFields.some((item) => {
        if (data.data._id === item._id) {
          update(item, data.data)
        }
      })
      // 更新步骤
    } else if (data.type === 'all') {
      state[currentType].allFields = data.data || []
    }
  }
}
